<template>
  <view class="withdraw-page">
    <!-- 顶部背景 -->
    <view class="withdraw-header">
      <view class="header-content">
        <view class="back-btn" @click="navigateBack">
          <image class="back-icon" src="/static/Images/wallet/Fanhuibai.png" mode="aspectFit"></image>
        </view>
        <view class="title">申请提现</view>
      </view>
    </view>
    
    <!-- 提现金额输入 -->
    <view class="withdraw-card">
      <view class="withdraw-amount-label">提现金额</view>
      <view class="withdraw-amount-input">
        <text class="currency-symbol">¥</text>
        <input 
          class="amount-input" 
          type="digit" 
          v-model="withdrawAmount" 
          placeholder="最小提现金额为¥10.00"
          @input="handleAmountInput"
        />
      </view>
      
      <view class="withdraw-balance">
        可提现余额: ¥{{ availableBalance }}，
        <text class="withdraw-all" @click="setMaxAmount">全部提现</text>
      </view>
    </view>
    
    <!-- 到账方式选择 -->
    <view class="payment-method-card">
      <view class="card-title">到账方式</view>
      
      <!-- 微信支付选项 -->
      <!-- <view class="payment-option" @click="selectPaymentMethod('wechat')">
        <view class="payment-left">
          <view class="payment-info">
            <image class="payment-icon" src="/static/Images/wallet/WeiPay.png" mode="aspectFit"></image>
            <view class="payment-name">提现至微信</view>
          </view>
        </view>
        <view class="payment-right">
          <view class="radio-button" :class="{active: paymentMethod === 'wechat'}"></view>
        </view>
      </view> -->
      
      <!-- 支付宝选项 -->
      <view class="payment-option" @click="selectPaymentMethod('alipay')">
        <view class="payment-left">
          <view class="payment-info">
            <image class="payment-icon" src="/static/Images/wallet/AliPay.png" mode="aspectFit"></image>
            <view class="payment-name">提现至支付宝</view>
          </view>
          <view class="payment-account">提现至支付宝账号{{ alipayAccount }}</view>
        </view>
        <view class="payment-right">
          <view class="radio-button" :class="{active: paymentMethod === 'alipay'}"></view>
        </view>
      </view>
    </view>
    
    <!-- 提交按钮 -->
    <button class="confirm-btn" @click="confirmWithdraw">确认提现</button>
    
    <!-- 底部指示器 -->
    <view class="bottom-indicator"></view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { getStorage, removeStorage, STORAGE_KEYS } from '@/utils/storage';
import { userApi } from '@/utils/api';

// 可提现余额（从路由参数或存储注入）
const availableBalance = ref(0);
// 支付宝账号
const alipayAccount = ref('');

// 提现金额
const withdrawAmount = ref('');

// 支付方式
const paymentMethod = ref('alipay'); // 默认选择支付宝

// 初始化：从路由参数读取 balance，若无则从存储读取，同时读取支付宝账号
onMounted(() => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const query = currentPage?.options || {};

  let v;
  if (query.balance !== undefined) {
    v = parseFloat(query.balance);
  } else {
    const stored = getStorage(STORAGE_KEYS.WITHDRAW_BALANCE);
    if (stored !== null && stored !== undefined) {
      v = parseFloat(stored);
      removeStorage(STORAGE_KEYS.WITHDRAW_BALANCE);
    }
  }
  availableBalance.value = Number.isFinite(v) ? v : 0;

  const ali = getStorage(STORAGE_KEYS.WITHDRAW_ALIPAY);
  if (ali !== null && ali !== undefined) {
    alipayAccount.value = String(ali);
    removeStorage(STORAGE_KEYS.WITHDRAW_ALIPAY);
  }
});

// 处理金额输入
const handleAmountInput = (e) => {
  // 限制只能输入数字和小数点
  const value = e.detail.value;
  if (value && !/^\d+(\.\d{0,2})?$/.test(value)) {
    withdrawAmount.value = withdrawAmount.value;
    return;
  }
  
  // 如果输入的金额大于可提现余额，则设置为可提现余额
  if (parseFloat(value) > availableBalance.value) {
    withdrawAmount.value = availableBalance.value.toString();
  }
};

// 设置最大提现金额
const setMaxAmount = () => {
  withdrawAmount.value = availableBalance.value.toString();
};

// 选择支付方式
const selectPaymentMethod = (method) => {
  paymentMethod.value = method;
};

// 确认提现
const confirmWithdraw = async () => {
  // 验证提现金额
  if (!withdrawAmount.value) {
    uni.showToast({
      title: '请输入提现金额',
      icon: 'none'
    });
    return;
  }
  
  const amount = parseFloat(withdrawAmount.value);
  
  // 验证最小提现金额
  if (amount < 10) {
    uni.showToast({
      title: '最小提现金额为¥10.00',
      icon: 'none'
    });
    return;
  }
  
  // 验证最大提现金额
  if (amount > availableBalance.value) {
    uni.showToast({
      title: '提现金额不能大于可提现余额',
      icon: 'none'
    });
    return;
  }
  
  // 检查是否已绑定账号（从已注入的 alipayAccount 判断）
  const hasAccountInfo = Boolean(alipayAccount.value);
  if (!hasAccountInfo) {
    // 跳转到账号设置页面
    uni.navigateTo({
      url: `/pages/wallet/account?method=${paymentMethod.value}`
    });
    return;
  }
  
  // 组装 type：支付宝=0，微信=1（预留）
  const typeVal = paymentMethod.value === 'alipay' ? 0 : 1;
  
  try {
    // 调用后端提现接口，传入 money、token（在 userApi 内部注入）、type
    const res = await userApi.withdraw({ money: amount, type: typeVal });
    uni.showToast({ title: res.msg || '提现申请已提交', icon: 'success', duration: 1000 });
    setTimeout(() => {
      uni.navigateTo({ url: '/pages/wallet/success' });
    }, 1000);
  } catch (error) {
    uni.showToast({ title: error.message || '提现失败', icon: 'none' });
  }
};

// 返回上一页
const navigateBack = () => {
  uni.navigateBack();
};
</script>

<style lang="scss">
.withdraw-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  position: relative;
}

/* 顶部背景 */
.withdraw-header {
  position: relative;
  width: 100%;
  height: 200rpx;
  background-color: #fff;
}

.header-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.header-content {
  position: relative;
  z-index: 2;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: 80rpx;
  position: relative;
}

.back-btn {
  position: absolute;
  left: 30rpx;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 40rpx;
  height: 40rpx;
}

.title {
  color: #111111;
  font-size: 36rpx;
  font-weight: 500;
  text-align: center;
  width: 100vw;
}

/* 提现金额卡片 */
.withdraw-card {
  margin: 30rpx;
  padding: 30rpx;
  background-color: #fff;
  border-radius: 12rpx;
}

.withdraw-amount-label {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 20rpx;
}

.withdraw-amount-input {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  border-bottom: 1rpx solid #eee;
  padding-bottom: 20rpx;
  font-size: 20px;
}

.currency-symbol {
  font-size: 64rpx;
  font-weight: bold;
  color: #333;
  margin-right: 10rpx;
}

.amount-input {
  flex: 1;
  font-size: 1.2rem;
  font-weight: bold;
  color: #333;
  height: 80rpx;
}

.withdraw-balance {
  font-size: 28rpx;
  color: #999;
}

.withdraw-all {
  color: #ff4d4f;
}

/* 支付方式卡片 */
.payment-method-card {
  margin: 0 30rpx 30rpx;
  padding: 30rpx;
  background-color: #fff;
  border-radius: 12rpx;
}

.card-title {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 30rpx;
}

.payment-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
}

.payment-left {
  display: flex;
  flex-direction: column;
}

.payment-info {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.payment-icon {
  width: 60rpx;
  height: 60rpx;
  margin-right: 20rpx;
}

.payment-name {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 6rpx;
}

.payment-account {
  font-size: 26rpx;
  color: #999;
  margin-top: 6rpx;
  margin-left: 80rpx;
}

.payment-right {
  display: flex;
  align-items: center;
}

.radio-button {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  border: 2rpx solid #ddd;
  display: flex;
  align-items: center;
  justify-content: center;
}

.radio-button.active {
  border-color: #ff4d4f;
  background-color: #fff;
  position: relative;
}

.radio-button.active::after {
  content: '';
  width: 24rpx;
  height: 24rpx;
  border-radius: 50%;
  background-color: #ff4d4f;
  position: absolute;
}

/* 确认按钮 */
.confirm-btn {
  width: calc(100% - 60rpx);
  height: 90rpx;
  line-height: 90rpx;
  background-color: #ff4d4f;
  color: #fff;
  font-size: 32rpx;
  border-radius: 45rpx;
  margin: 40rpx auto;
  border: none;
}

/* 底部指示器 */
.bottom-indicator {
  width: 120rpx;
  height: 8rpx;
  background-color: #ddd;
  border-radius: 4rpx;
  margin: 30rpx auto;
}
</style>